package com.example.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.common.ExcelImportUtil;
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jxls.common.Context;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.transform.poi.WritableCellValue;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public void exportUserAll(HttpServletResponse response) throws IOException {
        final List<User> users = userMapper.selectList(null);
        //获取模板
        final InputStream is = this.getInputStream();
        //returnMap
        final HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("users",users);
        //将文件放置到客户端下载
        this.setResponse(response);
        //excel表格导出
        this.exportExcel(is, response.getOutputStream(), returnMap);

    }
    @Override
    public void exportUserSome(HttpServletResponse response) throws IOException {
        final List<User> users = userMapper.selectList(null);
        //获取模板
        final InputStream is = this.getInputStream();
        //returnMap
        final HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("users",users);
        //将文件放置到客户端下载
        this.setResponse(response);
        //excel表格导出
        this.exportExcel(is, response.getOutputStream(), returnMap);

    }

    @Override
    @Transactional
    public void importUsers(MultipartFile file) {
        final Workbook wb = ExcelImportUtil.init(file);
        final Sheet sheet = wb.getSheetAt(0);
        final int rows = sheet.getLastRowNum();
        final ArrayList<User> users = new ArrayList<>();
        for (int i = 1; i <=rows ; i++) {
            final Row row = sheet.getRow(i);
            this.setUsers(users,row);
        }
        users.stream().forEach(user -> userMapper.insert(user));
    }



    public void setUsers(List<User> users, Row row){
        final User user = new User();
        final String id = ExcelImportUtil.convertCell2String(row.getCell(0));
        final String name = ExcelImportUtil.convertCell2String(row.getCell(1));
        final String pwd = ExcelImportUtil.convertCell2String(row.getCell(2));
        final String perms = ExcelImportUtil.convertCell2String(row.getCell(3));
        user.setId(Integer.valueOf(id));
        user.setPwd(pwd);
        user.setName(name);
        user.setPerms(perms);
        users.add(user);
    }

    private InputStream getInputStream() throws FileNotFoundException {
//        final URL url = this.getClass().getClassLoader().getResource("user/user.xlsx");
        final URL url = this.getClass().getClassLoader().getResource("user/user_mutipy.xlsx");
        return new FileInputStream(url.getFile());
    }
    private void setResponse(final HttpServletResponse response) {
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + "xlsExport.xls");
    }
    public static void exportExcel(final InputStream is, final OutputStream os, final Map<String, Object> model) throws IOException {
        final Context context = PoiTransformer.createInitialContext();
        if (model != null) {
            for (final String key : model.keySet()) {
                context.putVar(key, model.get(key));
            }
        }
        final JxlsHelper jxlsHelper = JxlsHelper.getInstance();
        final Transformer transformer = jxlsHelper.createTransformer(is, os);
        //必须要这个，否者表格函数统计会错乱
        jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);

    }
}
